package com.shockwave.pdfium.demo;

import com.shockwave.pdfium.PdfDocument;
import com.shockwave.pdfium.PdfiumCore;
import com.shockwave.pdfium.demo.util.GetByteArray;
import com.shockwave.pdfium.demo.util.GetFile;

import ohos.aafwk.ability.delegation.AbilityDelegatorRegistry;
import ohos.app.Context;
import ohos.global.resource.RawFileEntry;

import org.junit.Test;

import static org.junit.Assert.assertNotNull;

import java.io.File;
import java.io.FileDescriptor;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.io.FileInputStream;

/**
 * PdfCreationTest.
 */
public class PdfCreationTest {
    private static final String FILE_PATH = "entry/resources/rawfile/sample.pdf";
    private static final String FILE_NAME = "sample.pdf";
    PdfiumCore pdfiumCore;
    PdfDocument pdfDocument;
    private Context context;

    /**
     * createPdfbyAsset
     * @throws IOException
     */
    @Test
    public void createPdfbyAsset() throws IOException {
        context = AbilityDelegatorRegistry.getAbilityDelegator().getAppContext();
        RawFileEntry rawFileEntry = context.getResourceManager().getRawFileEntry(FILE_PATH);
        File file = GetFile.getFileFromRawFile(FILE_NAME, rawFileEntry, context.getCacheDir());
        FileDescriptor fd = new RandomAccessFile(file, "r").getFD();
        pdfiumCore = new PdfiumCore(context);
        pdfDocument = pdfiumCore.newDocument(fd);

        assertNotNull(pdfDocument);
    }

    /**
     * createPdfbyByte
     * @throws IOException
     */
    @Test
    public void createPdfbyByte() throws IOException {
        context = AbilityDelegatorRegistry.getAbilityDelegator().getAppContext();
        RawFileEntry rawFileEntry = context.getResourceManager().getRawFileEntry(FILE_PATH);
        File file = GetFile.getFileFromRawFile(FILE_NAME, rawFileEntry, context.getCacheDir());
        FileDescriptor fd = new RandomAccessFile(file, "r").getFD();

        FileInputStream fis = new FileInputStream(fd);
        byte [] data = GetByteArray.toByteArray(fis);

        pdfiumCore = new PdfiumCore(context);
        pdfDocument = pdfiumCore.newDocument(data);

        assertNotNull(pdfDocument);
    }

    /**
     * openPdfPage
     * @throws IOException
     */
    @Test
    public void openPdfPage() throws IOException {
        context = AbilityDelegatorRegistry.getAbilityDelegator().getAppContext();
        RawFileEntry rawFileEntry = context.getResourceManager().getRawFileEntry(FILE_PATH);
        File file = GetFile.getFileFromRawFile(FILE_NAME, rawFileEntry, context.getCacheDir());
        FileDescriptor fd = new RandomAccessFile(file, "r").getFD();
        pdfiumCore = new PdfiumCore(context);
        pdfDocument = pdfiumCore.newDocument(fd);
        long lpage = pdfiumCore.openPage(pdfDocument, 0);

        assertNotNull(lpage);
    }
}
